﻿using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Corina.DataContext.Service
{
    public class ProvinceService : ServiceBase
    {
        public List<ProvinceInfo> GetAllItems(string connectionString, string key)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("SELECT * FROM t_province AS tp ");
            builder.Append("WHERE tp.Name LIKE @Key OR tp.English LIKE @Key ");

            return DbOperator.GetEntities<ProvinceInfo>(connectionString, builder.ToString(), new SqlParameter("@Key", string.Format("%{0}%", key)));
        }

        public bool Update(string connectionString, ProvinceInfo entity, EntityOperation operation)
        {
            return DbOperator.UpdateEntity(connectionString, entity, operation);
        }

        public string GetCode(string connectionString)
        {
            string queryString = "SELECT MAX(Convert(int,tp.Code)) FROM t_province AS tp";
            DataTable table = DbOperator.GetDataTable(connectionString, queryString);
            if (table == null || table.Rows.Count == 0 || string.IsNullOrEmpty(table.Rows[0][0].ToString()))
            {
                return "01";
            }
            else
            {
                return (Convert.ToInt32(table.Rows[0][0]) + 1).ToString().PadLeft(2, '0');
            }
        }
    }
}
